import { createSlice } from '@reduxjs/toolkit';
// 1.使用createSlice方法创建一个slice。每一个slice里面包含了reducer和actions

export const counterSlice = createSlice({
	// 命名空间，在调用action的时候会默认的设置为action的前缀,保证唯一.不重名
	name: 'base',

	// state数据的初始值
	initialState: {
		token: '',
		themeConfig: {
			// 默认 primary 主题颜色
			primary: '#1890ff',
			// 深色模式
			isDark: false,
			// 面包屑导航
			breadcrumb: true,
			// 标签页
			tabs: true
		},
		/**********tags**********/
		activeTagId: location.pathname,
		tags: [],
		/*********用户信息*******/
		userInfo: {},
		avatar: '',
		permissions: [],
		roles: []
	},

	// 定义的 action 赋值的方式进行数据的改变
	reducers: {
		updateToken: (state, { payload }) => {
			state.token = payload;
		},
		setThemeConfig: (state, { payload }) => {
			state.themeConfig = payload;
			const body = document.body;
			if (payload.isDark) {
				body.setAttribute('theme-mode', 'dark');
			} else {
				body.removeAttribute('theme-mode');
			}
		},
		/***************************************tags逻辑***********************/
		setActiveTag(state, { payload }) {
			state.activeTagId = payload;
		},
		addTag(state, { payload }) {
			state.tags.push(payload);
			state.activeTagId = payload.path;
		},
		removeTag(state, { payload }) {
			const targetKey = payload;

			const activeTagId = state.activeTagId;
			let lastIndex = 0;

			state.tags.forEach((tag, i) => {
				if (tag.path === targetKey) {
					state.tags.splice(i, 1);
					lastIndex = i - 1;
				}
			});
			const tagList = state.tags.filter((tag) => tag.path !== targetKey);

			if (tagList.length && activeTagId === targetKey) {
				if (lastIndex >= 0) {
					state.activeTagId = tagList[lastIndex].path;
				} else {
					state.activeTagId = tagList[0].path;
				}
			}
		},
		removeLeftTag(state, { payload }) {
			const i = state.tags.findIndex((tag) => tag.path === payload);
			state.tags = state.tags.filter((tag, index) => index >= i);
		},
		removeRightTag(state, { payload }) {
			const i = state.tags.findIndex((tag) => tag.path === payload);
			state.tags = state.tags.filter((tag, index) => index <= i);
		},
		removeOtherTag(state) {
			const activeTag = state.tags.find((tag) => tag.path === state.activeTagId);
			const activeIsDashboard = activeTag?.path === state.tags[0].path;
			state.tags = activeIsDashboard ? [state.tags[0]] : [state.tags[0], activeTag];
		},
		removeAllTag(state) {
			state.activeTagId = state.tags[0].path;
			state.tags = [state.tags[0]];
		},
		/***************************************用户信息逻辑***********************/
		setBaseItem: (state, { payload }) => {
			Object.assign(state, payload);
		}
	}
});

// 导出方法
export const {
	updateToken,
	setThemeConfig,
	setActiveTag,
	addTag,
	removeTag,
	removeLeftTag,
	removeRightTag,
	removeAllTag,
	removeOtherTag,
	setBaseItem
} = counterSlice.actions;

// 导出切片数据
export default counterSlice.reducer;
